import { defineStore } from 'pinia'
import router from '@/router'

import { localCache } from '@/utils/cache'

import { accountLoginRequest, getUserInfoById, getUserMenusByRouleID } from '@/service/login/login'

import type { IAccount, IuserInfoData, IuserMenuTreeDaum } from '@/types/index'
import mapMenuToRoutes, { mapMenuListToPermissions } from '@/utils/mapMnent'
import useMainStore from '../main/main'

const LOGIN_TOKEN = 'token'

interface IStateTtype {
  token: string
  userInfo: IuserInfoData[]
  userMenuTree: IuserMenuTreeDaum[]
  permissions: string[]
}

export const useLoginStore = defineStore('login', {
  state: (): IStateTtype => ({
    token: '',
    userInfo: [],
    userMenuTree: [],
    permissions: []
  }),
  actions: {
    // 登录逻辑
    async loginAccountAction(account: IAccount) {
      let data = await accountLoginRequest(account)
      if (data.code === 0) {
        const id = data?.data.id
        const token = data?.data.token
        //存储token
        localCache.setCache(LOGIN_TOKEN, token)

        // 获取登录用户的详细信息
        const userInfo = (await getUserInfoById(id)).data

        // 获取用户登录的菜单树信息
        const userMenuTree = (await getUserMenusByRouleID(userInfo.role.id)).data

        localCache.setCache('userInfo', userInfo)
        localCache.setCache('userMenuTree', userMenuTree)

        // 获取角色列表和部门列表
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 获取登录用户的所有按钮权限
        const permissions = mapMenuListToPermissions(userMenuTree)
        this.permissions = permissions
        localCache.setCache('permissionsList', permissions)

        //根据用户的权限动态的添加路由
        const routes = mapMenuToRoutes(userMenuTree)
        routes.forEach((item) => {
          router.addRoute('main', item)
        })

        router.push('/main')
      }

      return data
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenuTree = localCache.getCache('userMenuTree')
      const permissionsList = localCache.getCache('permissionsList')
      if (token && userInfo && userMenuTree) {
        // 用户刷新后默认加载数据
        this.token = token
        this.userInfo = userInfo
        this.userMenuTree = userMenuTree
        this.permissions = permissionsList

        // 每次刷新后请求角色和部门的数据列表
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 动态添加路由
        const routes = mapMenuToRoutes(userMenuTree)
        routes.forEach((item) => {
          router.addRoute('main', item)
        })
      }
    }
  }
})
